package com.entrogy.service.impl;

import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.KaoqinService;
import com.entrogy.timing.StuRecordService;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName KaoqinServiceImpl
 * @Description
 * @Author luoxingjiang
 * @Date 2019/7/5 0005 上午 9:14
 * @Version 1.0
 **/
@Service
public class KaoqinServiceImpl implements KaoqinService {

    private static final Logger logger = LoggerFactory.getLogger(KaoqinServiceImpl.class);
    private String url = "/record/list";

    @Autowired
    private KaoqinMapper kaoqinMapper;
    @Autowired
    private VisitMapper visitMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private THDio thdio;


//    @Override
//    public JSONObject kaoqinInit(String uid) throws UserException {
//        return null;
//    }

    @Override
    public JSONObject susheInit(String uid) {
        JSONObject jsonObject = new JSONObject();
//        JSONArray list1 = new JSONArray();
//        JSONArray list2 = list2();
//        JSONArray list3 = new JSONArray();
//        JSONArray list4 = new JSONArray();
//        JSONArray list5 = new JSONArray();
//        for (int i = 1; i <= 6; i++) {
//            JSONObject tmp = new JSONObject();
//            tmp.put("id", i + "");
//            tmp.put("floor", i + "楼");
//            list5.add(tmp);
//        }
//        jsonObject.put("title", "宿舍考勤");
//        list1 = list1();
//        list2 = list2();
//        list3 = recordByLifetea("SS1_", "1", "1");
//        list4 = colTitle(1);
//        jsonObject.put("list1", list1);
//        jsonObject.put("list2", list2);
//        jsonObject.put("list3", list3);
//        jsonObject.put("list4", list4);
//        jsonObject.put("list5", list5);
        return jsonObject;
    }

    /**
     *判断查询对象是否在权限范围内,如果在则什么也不做，如果不在则抛出异常
     *
     * @param name
     * @param uid
     * @param startTime
     * @param endTime
     * @param page
     * @param schoolCode
     * @return
     */
    @Override
    public JSONObject getStudentRecord(String name, String uid, String startTime, String endTime, int page, Integer schoolCode) throws Exception{
        JSONArray jsonArray = new JSONArray();
        JSONObject returnjsonObject = new JSONObject();
        // 返回该教师的身份类型
        UserEntity userEntity = userMapper.getUserByUid(uid);
        int type;
        StudentEntity studentEntity = new StudentEntity();
        type = getTeacherType(Integer.parseInt(uid));
        // 这些用户没有查询权限
        if (type == -1 || type == 0 || type == 1)
            throw new Exception("无权限");
            // 班主任:看这个老师教的班级里是否有这个学生
        else if (type == 2) {
             studentEntity = studentMapper.getStudentByNameAndUid(userEntity.getClassId(),name/*学生姓名*/,userEntity.getSchoolCode());//根据老师所在的班级和学生姓名去查询学生
            // 如果为空则说明不能执行查询
            if (studentEntity == null)
                throw new Exception("输入学生信息有误或没有相关权限");
        }
        // 年级主任:看这个老师所管的年级里是否有这个学生
        else if (type == 3) {
           studentEntity = studentMapper.getStudentByUidAndGradeid(userEntity.getGradeId().substring(0,3),name/*学生姓名*/,userEntity.getSchoolCode());
            // 如果为空则说明不能执行查询
            if (studentEntity == null)
                throw new Exception("输入学生信息有误或没有相关权限");
    }
        // 能顺利运行到这里则说明通过了检查，向实义德服务器发送请求
        // 不为空则向实义德服务器发送请求
        JSONObject jsonObject = new JSONObject();
        //获取实义德后台地址
        if (page == 0) {
            page = 1;
        }
        jsonObject.put("page", page);
        jsonObject.put("amount", 20);
        jsonObject.put("keyword", name);
        if (startTime != null) {
            jsonObject.put("identify_start_time", daytoSecond(startTime, "yyyy-MM-dd"));
        }
        if (endTime != null) {
            jsonObject.put("identify_end_time", daytoSecond(endTime, "yyyy-MM-dd"));
        }
        // 发送请求并处理返回数据
        SchoolThdidUrlEntity schoolThididUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        JSONObject record = thdio.THD_interface(schoolThididUrl.getPathUrl(), url, jsonObject, true, schoolThididUrl.getAccessToken());
        int code = record.getInt("code");
        if (code == 0) {
            JSONObject date = record.getJSONObject("data");
            int total = date.getInt("total");
            returnjsonObject.put("total", total);
            JSONArray recordList = date.getJSONArray("record_list");
            for (int i = 0; i < recordList.size(); i++) {
                JSONObject recordObj = recordList.getJSONObject(i);
                String stuName = recordObj.getString("personnel_name");
                int identify_ts = recordObj.getInt("identify_ts");
                String deviceName = recordObj.getString("device_name");
                String stuTHDid = recordObj.getString("personnel_id");
                String className = studentMapper.getCourseNameByStudentThdid(stuTHDid,schoolCode);
                JSONObject tmp = new JSONObject();
                Date tmpdate = new Date();
                tmpdate.setTime((long) identify_ts * 1000);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                tmp.put("name", stuName);
                tmp.put("classname", className);
                tmp.put("time", sdf.format(tmpdate));
                tmp.put("devicename", deviceName);
                jsonArray.add(tmp);
            }
            returnjsonObject.put("data", jsonArray);
        } else {
            throw new Exception("查询学生信息失败");
        }
        return returnjsonObject;
   }
    // 返校日初始化,两个list，list1封装可以选择的年级，list2封装记录
    public JSONObject backtoSchoolInit(String uid)  {
        int type = -1;
        JSONObject jsonObject = new JSONObject();
        JSONArray list1 = new JSONArray();
        JSONArray list2 = new JSONArray();
        try {
            type = getTeacherType(Integer.parseInt(uid));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("该"+uid+"的老师查询教师类型出错");
        }
        UserEntity userEntity = userMapper.getUserByUid(uid);
        // 班主任只有自己班的返校
        if (type == 2) {
            JSONObject classObj = new JSONObject();
            JSONObject tmp = new JSONObject();
            tmp.put("id",userEntity.getClassId());//班级ID
            String className = classMapper.getClassNameById(userEntity.getClassId(),userEntity.getSchoolCode());
            tmp.put("name", className);
            list1.add(tmp);
            classObj = getClassRecord(uid, userEntity.getClassId(),className,userEntity.getSchoolCode());
            list2.add(classObj);
        }
        // 年级主任
        else if (type == 3) {
            String[] strList;
            // 先得到年级,再得到该年级的全部班级
            JSONObject tmp = new JSONObject();
            tmp.put("id", userEntity.getGradeId());
            tmp.put("name", classMapper.getClassNameById(userEntity.getClassId(),userEntity.getSchoolCode()));
            list1.add(tmp);
        }
        // 中层领导
        else if (type == 4) {
            List<ClassEntity> lists = classMapper.getGradeList(userEntity.getSchoolCode());//获取该学校的年级列表
            list2 = getGradeRecord(lists,userEntity.getSchoolCode());//得到每个年级的记录
        }
        jsonObject.put("list1", list1);
        jsonObject.put("list2", list2);
        return jsonObject;
    }

    @Override
    public JSONArray backtoSchoolSelect(String uid, String courseId) {
        // 得到每个年级的记录
        JSONArray jsonArray = new JSONArray();
        UserEntity userEntity = userMapper.getUserByUid(uid);
        List<Object[]> classList = kaoqinMapper.getGradeInfo(courseId,userEntity.getSchoolCode());
        // 遍历班级得到每个班的记录装进list2中
        for (int i = 0; i < classList.size(); i++) {
            String userId = userMapper.getUserByClassID(Integer.parseInt(courseId),userEntity.getSchoolCode());
            JSONObject tmpObj = getClassRecord(userId, courseId, (String) classList.get(i)[1],userEntity.getSchoolCode());
            jsonArray.add(tmpObj);
        }
        return jsonArray;
    }

    // 把string类型的时间转为时间戳，单位为秒
    private int daytoSecond(String date, String formate) {
        SimpleDateFormat sdf = new SimpleDateFormat(formate);
        String second = null;
        try {
            second = String.valueOf(sdf.parse(date).getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(second);
    }
    // 封装某个班的返校记录
    private JSONObject getClassRecord(String uid, String courseid, String classname,int schoolCode) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String tableName = "pass_record" + dateFormat.format(date);
        Date chechTime = null;//TODO ---需要注意
//        Date chechTime = schoolMapper.getBackSchoolTime(schoolCode);//TODO ------------------------需要更改的地方
        JSONObject classObj = new JSONObject();
        try {
            int total = studentMapper.getStudentCountByClassID(courseid,schoolCode);//总人数
            int real = studentMapper.getIntoSchoolCount(tableName, 10, courseid,schoolCode);//进校人数  TODO  10代表的意思 要和流水进去的标识 一致喔
            int leaveNum = kaoqinMapper.getLeaveNum(courseid,schoolCode);//请假人数
            classObj.put("classname", classname);
            classObj.put("total", total);
            classObj.put("real", real);
            classObj.put("leave", leaveNum);
            // 在18:50之后才显示异常学生名单
            if (date.after(chechTime)) {
                String abnormalName = getAbnormalStuName(tableName, courseid, uid,schoolCode);
                classObj.put("abnormal", abnormalName);
            } else
                classObj.put("abnormal", "");
        } catch (Exception e) {
            logger.error("查询班级返校记录失败");
        }
        return classObj;
    }
    // 得到每个年级的记录
    private JSONArray getGradeRecord(List<ClassEntity> gradeList,int schoolCode) {
        JSONArray jsonArray = new JSONArray();
        for(ClassEntity classEntity : gradeList){
            List<ClassEntity> classIds = classMapper.getClassListByGradeId(classEntity.getId(),schoolCode);
            // 遍历班级得到每个班的记录装进list2中
            for (int i = 0; i < classIds.size(); i++) {
                String uid = userMapper.getUserByClassID(classIds.get(i).getId(),schoolCode);
                JSONObject tmpObj = getClassRecord(uid, classIds.get(i).getId()+"",
                        classIds.get(i).getClassName(),schoolCode);
                jsonArray.add(tmpObj);
            }
        }
        return jsonArray;
    }
    // 获得返校异常的学生名单，传入参数为班级id,班主任id，异常学生指既没通过进行闸机也没有请假
    private String getAbnormalStuName(String tableName, String course_id, String uid,int schoolCode) throws SQLException {
        String name = null;
        // 先查通过闸机的人的名单
        List<String> stuNames = kaoqinMapper.getPassRecordStuName(tableName,course_id,schoolCode); //TODO flag ---问题
        for (int i = 0; i < stuNames.size() - 1; i++)
            name += "'" + stuNames.get(i) + "',";
        if (stuNames.size() >= 1)
            name += "'" + stuNames.get(stuNames.size() - 1) + "'";
        // 再查询请假的人的名单
        List<String> students = kaoqinMapper.getStudentNamesForLeave(uid,new Date(),new Date(),schoolCode);
        for (int i = 0; i < students.size() - 1; i++)
            name += "'" + students.get(i) + "',";
        if (students.size() >= 1)
            name += "'" + students.get(students.size() - 1) + "'";
        // 得到异常人员
        List<String> abnormalList = kaoqinMapper.getAbnormalByCourseId(course_id,name,schoolCode);
        String abnormalName = null;
        int count = 0;
        for (; count < abnormalList.size(); count++)
            abnormalName += abnormalList.get(count) + " ";
        return abnormalName + "共" + count + "人";
    }


//
//    public JSONObject qingjiaInit(String uid) throws UserException {
//        JSONObject jsonObject = new JSONObject();
//        JSONArray list1 = new JSONArray();
//        JSONArray list2 = list2();
//        JSONArray list3 = new JSONArray();
//        JSONArray list4 = new JSONArray();
//        jsonObject.put("title", "请假查看");
//        list1 = gradeList();
//        list2 = list2();
//        list3 = getLeaveRecord("1000000"); // 获取全校的请假
//        list4 = colTitle(3);
//        jsonObject.put("list1", list1);
//        jsonObject.put("list2", list2);
//        jsonObject.put("list3", list3);
//        jsonObject.put("list4", list4);
//        return jsonObject;
//    }

    // 返回某班早上迟到的人数，有两个出门迟到
    public int getMoningLateNum(String tableName, String classId){
        // 早上大门迟到的人数
        int morningGateLate = kaoqinMapper.getIntersection(tableName, 7, classId);
        // 早上宿舍迟到的人数
        int morningDormitoryLate = kaoqinMapper.getIntersection(tableName, 1, classId);
        return morningGateLate + morningDormitoryLate;
    }

    /*
     * 查询界面初始化，时间条件默认是上午,年级条件默认是第一个 list1保存查询的班级信息 list2的返回值大家都一样，早中晚三个
     * list3保存各个考勤类别的人数信息  TODO ----废弃了 XLR
     */
    @Override
    public JSONObject kaoqinInit(String uid){
//        JSONObject jsonObject = new JSONObject();
//        JSONArray list1 = new JSONArray();
//        JSONArray list2 = list2();
//        JSONArray list3 = new JSONArray();
//        JSONArray list4;
////        int dayType = getDayType();
//        int dayType = 0;//TODO  ---这个字段要注意哦  弄的默认值 ---注释掉 了  现在 没有什么返校日 之类的了，
//        // 区别家长还是教师
//        if (uid.startsWith("1")) {
//            int type = -2;
//            UserEntity userEntity = visitMapper.getUserById(uid);
//
////             * 判断教师用户类型 17-普通老师：无查看考勤的权限 1-生活老师：寝室考勤，有不同的界面 16-班主任：只看自己班的考勤 15-年级主任：看全年级班级的考勤
////             * 1-中层：看所有年级的所有班级的考勤
//
//            type = userEntity.getSid();
//            Integer schoolCode = userMapper.getUserByUid(uid).getSchoolCode();
//            // 根据教师权限不同类型，做不同的处理
//            // 普通老师或者没有权限,返回一个空的JSONArray
//                if (type == 16) {
//                // 填list,得到班主任所带班级的信息
//                List<ClassEntity> classEntities = kaoqinMapper.getLeaderClassInfo(uid, schoolCode);
//                JSONObject tmp = new JSONObject();
//                //班主任带的第一个班的id
//                int firstClassId = classEntities.get(0).getId();
//                tmp.put("id", firstClassId);
//                tmp.put("name", classEntities.get(0).getClassName());
//                list1.add(tmp);
//                // 填list3,时间默认是上午，所以只有出寝室迟到的人和进校门迟到的人
//                // 获取早上迟到的人数
//                JSONObject object = new JSONObject();
//                object.put("id", firstClassId);
//                object.put("col1", classEntities.get(0).getClassName());
//                int morningLate = getMoningLateNum(getTableName(), firstClassId + "");
//                int leaveNum = getLeaveNum(firstClassId + "",schoolCode);
//                int total = schoolMapper.getClassStuNum(firstClassId, schoolCode) - leaveNum;
//                int real = total - morningLate;
//                if (dayType == 1) {
//                    real = kaoqinMapper.getIntersection(getTableName(), 10, firstClassId + "");
//                }
//                record(object, morningLate, 0, leaveNum, real, total);
//                list3.add(object);
//            }
//            // 年级主任，list1只有一个年级的，list3默认为自己年级上午的考勤记录
//            else if (type == 15) {
//                // 填充lsit1,只有一个年级
//                // 填list1
//                List<GradeEntity> gradeEntities = kaoqinMapper.getLeaderGradeInfo(uid, schoolCode);
//                int gradeId = gradeEntities.get(0).getClassId();
//                JSONObject tmp = new JSONObject();
//                tmp.put("id", gradeId);
//                tmp.put("name", gradeEntities.get(0).getClassName());
//                list1.add(tmp);
//                // 填充list3
//                list3 = getGradeMorningKaoqinInfo(gradeId + "", schoolCode);
//            }
//            // 中层领导，list1为全校的所有年级，list3默认list1的第一个年级的上午考勤 TODO 暂定中层领导的定义为校长
//            else if (type == 1) {
//                // 填充list1,使用gradeService中的函数，第一个是1110000
//                list1 = schoolMapper.schoolAllGradeList(schoolCode);
//                // 填充list3
//                list3 = getGradeMorningKaoqinInfo(list1.getJSONObject(0).getString("id"), schoolCode);
//            }
//        }
//        list4 = colTitle(2);
//        jsonObject.put("title", "平安考勤");
//        jsonObject.put("list1", list1);
//        jsonObject.put("list2", list2);
//        jsonObject.put("list3", list3);
//        jsonObject.put("list4", list4);
        return null;
    }

    @Override
    public JSONArray getKaoqin(String uid, String select1id, String timeid, String date) {
        String tableName = getTableName(date);
        JSONArray jsonArray = new JSONArray();
        UserEntity userEntity = userMapper.getUserByUid(uid);
        int pid = userEntity.getpId();
        int type = getTeacherType(pid);
        // 普通老师没有权限
        if (type == 0 || type == -1)
            return jsonArray;
            // 生活老师
        else if (type == 1) {
            return jsonArray;
        }
        // 班主任
        else if (type == 2) {
            // 填充返回值
            jsonArray = getClassInfo(tableName, select1id, timeid,userEntity.getSchoolCode());
        }
        // 年级主任
        else if (type == 3 || type == 4) {
            // 填充返回值
            jsonArray = getGradeInfo(tableName, select1id, timeid,userEntity.getSchoolCode());
        }
        return jsonArray;
    }

    // 班主任筛选本班的情况
    private JSONArray getClassInfo(String tableName, String courseid, String timeid,int schoolCode){
        JSONArray jsonArray = new JSONArray();
        // 查询请假
        List<LeaveRecordEntity> leaveRecordBeanList = kaoqinMapper.getLeaveRecordByCId(courseid,schoolCode);
        Date date = new Date(); // 获取当天时间
        for (LeaveRecordEntity  recordEntity : leaveRecordBeanList) {
            if (date.before(recordEntity.getStartTime()) && date.after(recordEntity.getEndTime()))
                leaveRecordBeanList.remove(recordEntity);
        }
        if (timeid.equals("1")) {
            getRecord(jsonArray, leaveRecordBeanList, kaoqinMapper.getMorningInfoByTea(tableName, courseid,schoolCode));
        } else if (timeid.equals("2"))
            getRecord(jsonArray, leaveRecordBeanList, kaoqinMapper.getNoonInfoByTea(tableName, courseid,schoolCode));
        else
            getRecord(jsonArray, leaveRecordBeanList, kaoqinMapper.getNightInfoByTea(tableName, courseid,schoolCode));
        return jsonArray;
    }

    // 获取某年级的上午考勤情况,先得到某个年级的每个班级id
    private JSONArray getGradeInfo(String tableName, String courseId, String timeid,int schoolCode){
        JSONArray jsonArray = new JSONArray();
        ArrayList<Object[]> geradeInfo = new ArrayList<>();
        if (!"1000000".equals(courseId)) {        //TODO ------------需要注意的地方
            geradeInfo = kaoqinMapper.getGradeInfo(courseId.substring(0,3),schoolCode);//获取某个年级的班级信息
        }else{//获取全学校的班级信息
            geradeInfo = kaoqinMapper.getTotalClassInfo(schoolCode);
        }
        if (timeid.equals("1")) {
            for (Object[] gradeList : geradeInfo) {
                List<LeaveRecordEntity> leaveRecordBeanList = kaoqinMapper.getLeaveRecordByCId((String) gradeList[0],schoolCode);
                List<PassRecordEntity> classInfo = kaoqinMapper.getMorningInfoByTea(tableName, (String) gradeList[0],schoolCode);
                getRecord(jsonArray, leaveRecordBeanList, classInfo);
            }
        } else if (timeid.equals("2")) {
            for (Object[] gradeList : geradeInfo) {
                List<LeaveRecordEntity> leaveRecordBeanList = kaoqinMapper.getLeaveRecordByCId((String) gradeList[0],schoolCode);
                List<PassRecordEntity> classInfo = kaoqinMapper.getNoonInfoByTea(tableName, (String) gradeList[0],schoolCode);
                getRecord(jsonArray, leaveRecordBeanList, classInfo);
            }
        } else {
            for (Object[] gradeList : geradeInfo) {
                List<LeaveRecordEntity> leaveRecordBeanList = kaoqinMapper.getLeaveRecordByCId((String) gradeList[0],schoolCode);
                List<PassRecordEntity> classInfo = kaoqinMapper.getNightInfoByTea(tableName, (String) gradeList[0],schoolCode);
                getRecord(jsonArray, leaveRecordBeanList, classInfo);
            }
        }
        return jsonArray;
    }

    private int getTeacherType(int pid) {
        int type = -1;
        // 中层领导
        if (pid  != 9 && pid  != 0 && pid  != 5 && pid  != 8
                && pid  != 12 && pid  != 15 && pid  != 18 && pid  != 23)
            type =  4;
        // 普通老师
        if (pid  == 0 && pid == 18)
            type =  0;
            // 生活老师
        else if (pid  == 9)
            type =  1;
            // 班主任
        else if (pid == 17)
            type =  2;
            // 年级主任
        else if (pid == 16)
            type =  3;
            // 保安队
        else if (pid  == 23)
            type =  5;
        else
            type =  -1;
        return type;
    }

    // 根据passrecord返回封装好的list3
    private JSONArray getRecord(JSONArray jsonArray, List<LeaveRecordEntity> leaveRecordBeans,
                                List<PassRecordEntity> recordBeans){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 装入请假数据
        for (LeaveRecordEntity leaveRecordBean : leaveRecordBeans) {
            JSONObject jsonObject = new JSONObject();
            StudentEntity studentEntity = studentMapper.getStudentAndCourseNameById(Integer.parseInt(leaveRecordBean.getStudentId()));
            jsonObject.put("name", studentEntity.getStudentName());
            jsonObject.put("classname", studentEntity.getCourseName());
            jsonObject.put("type", "请假");
            jsonObject.put("time", dateFormat.format(leaveRecordBean.getStartTime()));
        }
        // 装入考勤数据
        for (PassRecordEntity recordBean : recordBeans) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", recordBean.getPersonName());
            jsonObject.put("classname", classMapper.getClassName(recordBean.getCourseId(),recordBean.getPersonId()));
            if (recordBean.getFlag() == 1 || recordBean.getFlag() == 3 || recordBean.getFlag() == 7
                    || recordBean.getFlag() == 8 || recordBean.getFlag() == 9)
                jsonObject.put("type", "上课迟到");
            else if (recordBean.getFlag() == 2 || recordBean.getFlag() == 4)
                jsonObject.put("type", "归寝迟到");
            jsonObject.put("time", dateFormat.format(recordBean.getIdentifyTs()));
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    //    // 生活老师list1的内容
//    public JSONArray list1() {
//        JSONArray jsonArray = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("id", "SS1_");
//        jsonObject.put("name", "宿舍一栋");
//        jsonArray.add(jsonObject);
//        jsonObject.clear();
//        jsonObject.put("id", "SS2_");
//        jsonObject.put("name", "宿舍二栋");
//        jsonArray.add(jsonObject);
//        jsonObject.clear();
//        jsonObject.put("id", "SS3_");
//        jsonObject.put("name", "宿舍三栋");
//        jsonArray.add(jsonObject);
//        jsonObject.clear();
//        jsonObject.put("id", "SS4_");
//        jsonObject.put("name", "宿舍四栋");
//        jsonArray.add(jsonObject);
//        return jsonArray;
//    }
//
//    // list2的内容
    public JSONArray list2() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("timeid", 1);
        jsonObject.put("time", "上午");
        jsonArray.add(jsonObject);
        jsonObject.clear();
        jsonObject.put("timeid", 2);
        jsonObject.put("time", "中午");
        jsonArray.add(jsonObject);
        jsonObject.clear();
        jsonObject.put("timeid", 3);
        jsonObject.put("time", "晚上");
        jsonArray.add(jsonObject);
        jsonObject.clear();
        return jsonArray;
    }
//
//    // 宿舍筛选
//    public JSONArray selectSushe(String uid, String list1id, String timeid, String floorid) throws UserException {
//        return recordByLifetea(list1id, timeid, floorid);
//    }
//
//    // 请假筛选
//    public JSONArray selectQingjia(String uid, String list1id) throws UserException {
//        return getLeaveRecord(list1id);
//    }
//
//    // 按条件筛选,只需返回lsit3;
    @Override
    public JSONArray select(String uid, String list1id, String timeid){
//        JSONArray jsonArray;
//        UserEntity userEntity = userMapper.getUserByUid(uid);
//        int type = visitMapper.getUserById(uid).getSid();
//        Integer schoolCode = userEntity.getSchoolCode();
//        // 根据教师权限不同类型，做不同的处理
//        if (type == 16) {
//            jsonArray = selectClass(uid, list1id, timeid);
//        }
//        // 中层领导和年级组长都一样，按照年级筛选
//        else {
//            jsonArray = selectGrade(list1id, timeid, schoolCode);
//        }
        return null;
    }
//
//    // 班主任按班级筛选
    public JSONArray selectClass(String uid, String course_id, String timeid) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
//        int dayType = getDayType();
        int dayType = 0;//TODO  ---这个字段要注意哦  弄的默认值 ---注释掉 了  现在 没有什么返校日 之类的了，
        Integer schoolCode = userMapper.getUserByUid(uid).getSchoolCode();
        // 上午的考勤
        if (timeid.equals("1")) {
            int morningLate;
            jsonObject.put("id", course_id);
            ClassEntity classEntity = classMapper.getClassById(Integer.valueOf(course_id), schoolCode);
            //避免jsonarray中的jsonobject对象中包含的对象为空出错
            classEntity.setClassTypeEntity(new ClassTypeEntity());
            jsonObject.put("col1", classEntity);
            morningLate = getMoningLateNum(getTableName(), course_id);
            int leaveNum = getLeaveNum(course_id,schoolCode);
            int total = schoolMapper.getClassStuNum(Integer.valueOf(course_id), schoolCode) - leaveNum;
            int real = total - morningLate;
            if (dayType == 1) {
                real = kaoqinMapper.getIntersection(getTableName(), 10, course_id);
            }
            record(jsonObject, morningLate, 0, leaveNum, real, total);
        }
        // 中午的考勤
        else if (timeid.equals("2")) {
            jsonObject.put("id", course_id);
            ClassEntity classEntity = classMapper.getClassById(Integer.valueOf(course_id), schoolCode);
            //避免jsonarray中的jsonobject对象中包含的对象为空出错
            classEntity.setClassTypeEntity(new ClassTypeEntity());
            jsonObject.put("col1", classEntity);
            int noonGateLate = getNoonInLateNum(getTableName(), course_id);
            int noonDroLate = getNoonOutLateNum(getTableName(), course_id);
            int leaveNum = getLeaveNum(course_id,schoolCode);
            int total = schoolMapper.getClassStuNum(Integer.valueOf(course_id), schoolCode) - leaveNum;
            int real = total - noonGateLate - noonDroLate;
            if (dayType == 1) {
                real = kaoqinMapper.getIntersection(getTableName(), 10, course_id);
            }
            record(jsonObject, noonGateLate, noonDroLate, leaveNum, real, total);
        }
        // 晚上考勤
        else if (timeid.equals("3")) {
            jsonObject.put("id", course_id);
            ClassEntity classEntity = classMapper.getClassById(Integer.valueOf(course_id), schoolCode);
            //避免jsonarray中的jsonobject对象中包含的对象为空出错
            classEntity.setClassTypeEntity(new ClassTypeEntity());
            jsonObject.put("col1", classEntity);
            int nightGateLate = getNightinLateNum(getTableName(), course_id);
            int nightDarLate = getNightOutLateNum(getTableName(), course_id);
            int liveinschool = kaoqinMapper.getLiveInSchoolNum(course_id);
            int nightKaoqin = getNightKaoqinNum(getTableName(), course_id);
            int leaveNum = getLeaveNum(course_id,schoolCode);
            record(jsonObject, nightGateLate, nightDarLate, leaveNum, nightKaoqin, liveinschool);
        }
        jsonArray.add(jsonObject);
        return jsonArray;
    }

    // 返回某班晚上归寝考勤的做人数
    private int getNightKaoqinNum(String tableName, String course_id){
        return kaoqinMapper.getIntersection(tableName, 5, course_id);
    }

    // 返回某班晚上归寝迟到的人数
    public int getNightOutLateNum(String tableName, String course_id){
        return kaoqinMapper.getIntersection(tableName, 4, course_id);
    }

    // 返回某班晚上上课迟到的人数，只有大门迟到
    private int getNightinLateNum(String tableName, String course_id){
        return kaoqinMapper.getIntersection(tableName, 9, course_id);
    }

    // 返回某班早上迟到的人数，有两个出门迟到
    private int getNoonInLateNum(String tableName, String course_id) {

        // 中午大门迟到的人数
        int noonGateLate = kaoqinMapper.getIntersection(tableName, 8, course_id);
        // 中午宿舍迟到的人数
        int noonDormitoryLate = kaoqinMapper.getIntersection(tableName, 3, course_id);
        return noonGateLate + noonDormitoryLate;
    }

    // 返回某班中午归寝迟到的人数
    private int getNoonOutLateNum(String tableName, String course_id) {
        return kaoqinMapper.getIntersection(tableName, 2, course_id);
    }

    //
//    // 返回不同年级的不同时段考勤信息，只需返回list3就行
    public JSONArray selectGrade(String course_id, String timeid, Integer schoolCode){
        JSONArray jsonArray;
        // 上午的考勤
        if (timeid.equals("1")) {
            jsonArray = getGradeMorningKaoqinInfo(course_id, schoolCode);

        }
        // 中午的考勤
        else if (timeid.equals("2")) {
            jsonArray = getGradeNoonKaoqinInfo(course_id, schoolCode);
        }
        // 晚上的考勤
        else {
            jsonArray = getGradeNightKaoqinInfo(course_id, schoolCode);
        }
        return jsonArray;
    }
//
//    // 查询某班当天请假的人数
    public Integer getLeaveNum(String course_id,int schoolCode) {
        return kaoqinMapper.getLeaveNum(course_id,schoolCode);
    }
//
//    /**
//     * 前端传过来的值 值1：楼栋号 :例如：SS1_ 值2:时间类别 :例如：Morning，Noon，Night
//     */
//
//    /**
//     * 早上出门迟到：1，中午入门迟到：2，中午出门迟到：3，晚上入门迟到：4 ，晚上正常是5
//     */
//
//    // 得到家长
//    public List<StudentBean> getAllRecordByPar(String parentId, String curTime) throws SQLException {
//        List<StudentBean> allList = kaoqinDao.getAllRecordByPar(parentId, curTime);
//        return allList;
//    }
//
//    // 生活老师得到：
//    // 早上 ：出门迟到；中午 ：入门迟到 ，出门迟到； 晚上：入门迟到，未归寝
//
//    /**
//     * @param buildId  前端传来的楼栋号
//     * @param timeType 前端传来的时间段 早，中，晚
//     * @return 返回给前端JSON格式的字符串
//     * @throws UserException
//     * @throws SQLException
//     */
//    public JSONArray recordByLifetea(String buildId, String timeType, String floorid) throws UserException {
//        JSONArray reJsonArray = new JSONArray();
//        SimpleDateFormat sformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//        if (timeType.equals("1")) {
////            早上 ：出门迟到
//            List<RecordByLifeteaBean> reList;
//            try {
//                reList = kaoqinDao.morningLifetea(getTableName(), buildId, floorid);
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new UserException("生活老师查询上午考勤信息失败");
//            }
//            for (RecordByLifeteaBean record : reList) {
//                JSONObject reJsonObject = new JSONObject();
//                reJsonObject.put("col1", record.getDormitory());
//                reJsonObject.put("col2", getClassName(record.getCourse_id()));
//                reJsonObject.put("col3", record.getStudent_name());
//                reJsonObject.put("col4", record.getType());
//                String time1 = sformat.format(record.getRecord_time()).substring(2, 10);
//                String time2 = sformat.format(record.getRecord_time()).substring(11);
//                reJsonObject.put("col5", time1 + "\n" + time2);
//                reJsonObject.put("col6", record.getStudent_gender());
//                reJsonArray.add(reJsonObject);
//            }
//        }
//        if (timeType.equals("2")) {
////      中午 ：入门迟到 ，出门迟到
//            List<RecordByLifeteaBean> reList;
//            try {
//                reList = kaoqinDao.noonLifetea(getTableName(), buildId, floorid);
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new UserException("生活老师查询中午考勤信息失败");
//            }
//            for (RecordByLifeteaBean record : reList) {
//                JSONObject reJsonObject = new JSONObject();
//                reJsonObject.put("col1", record.getDormitory());
//                reJsonObject.put("col2", getClassName(record.getCourse_id()));
//                reJsonObject.put("col3", record.getStudent_name());
//                reJsonObject.put("col4", record.getType());
//                String time1 = sformat.format(record.getRecord_time()).substring(2, 10);
//                String time2 = sformat.format(record.getRecord_time()).substring(11);
//                reJsonObject.put("col5", time1 + "\n" + time2);
//                reJsonObject.put("col6", record.getStudent_gender());
//                reJsonArray.add(reJsonObject);
//            }
//        }
//        if (timeType.equals("3")) {
////            晚上：入门迟到，未归寝
//            List<RecordByLifeteaBean> reList;
//            try {
//                Date current = new Date();
//                if (current.after(StuRecordService.date8)) {
//                    reList = kaoqinDao.nightLifetea(getTableName(), buildId, floorid);
//                    for (RecordByLifeteaBean record : reList) {
//                        JSONObject reJsonObject = new JSONObject();
//                        reJsonObject.put("col1", record.getDormitory());
//                        reJsonObject.put("col2", getClassName(record.getCourse_id()));
//                        reJsonObject.put("col3", record.getStudent_name());
//                        reJsonObject.put("col4", record.getType());
//                        String time1 = sformat.format(record.getRecord_time()).substring(2, 10);
//                        String time2 = sformat.format(record.getRecord_time()).substring(11);
//                        reJsonObject.put("col5", time1 + "\n" + time2);
//                        reJsonObject.put("col6", record.getStudent_gender());
//                        reJsonArray.add(reJsonObject);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new UserException("生活老师查询晚上考勤信息失败");
//            }
//        }
//        return reJsonArray;
//    }
//
////    老师得到每个班级的详细考勤信息

    /**
     * @param classId 前端传来的班级信息
     * @param schoolCode
     * @return 返回给前端JSON格式的字符串
     */
    public JSONArray detailRecordByTea(String classId, Integer schoolCode) {
        JSONArray reJsonArray = new JSONArray();
//        list中 list[0]:上课迟到, list[1]：归寝迟到 ;list[2]:未归寝, list[3]：请假, list[4]：旷课,
//      1、第一步上午信息
        List<List<String>> DetailRecordMorByTeaBean;
        DetailRecordMorByTeaBean = getDetailRecordMorByTea(getTableName(), classId, schoolCode);
        JSONObject reJsonObjectMor = new JSONObject();
        reJsonObjectMor.put("goClass", "上午");
        reJsonObjectMor.put("goClassLateCount", DetailRecordMorByTeaBean.get(0).size());
        reJsonObjectMor.put("goClassLateName", getStuNames(DetailRecordMorByTeaBean.get(0)));
        reJsonObjectMor.put("backRoomLateCount", DetailRecordMorByTeaBean.get(1).size());
        reJsonObjectMor.put("backRoomLateName", getStuNames(DetailRecordMorByTeaBean.get(1)));
        reJsonObjectMor.put("notRoomCount", DetailRecordMorByTeaBean.get(2).size());
        reJsonObjectMor.put("notRoomName", getStuNames(DetailRecordMorByTeaBean.get(2)));
        reJsonObjectMor.put("askLeaveCount", DetailRecordMorByTeaBean.get(3).size());
        reJsonObjectMor.put("askLeaveCountName", getStuNames(DetailRecordMorByTeaBean.get(3)));
        // reJsonObjectMor.put("旷课人数", DetailRecordMorByTeaBean.get(4).size());
        // reJsonObjectMor.put("旷课姓名", DetailRecordMorByTeaBean.get(4));
        reJsonArray.add(reJsonObjectMor);
//      2、第二步中午信息
        List<List<String>> DetailRecordNoonByTeaBean;
        DetailRecordNoonByTeaBean = getDetailRecordNoonByTea(getTableName(), classId, schoolCode);
        JSONObject reJsonObjectNoon = new JSONObject();
        reJsonObjectNoon.put("goClass", "中午");
        reJsonObjectNoon.put("goClassLateCount", DetailRecordNoonByTeaBean.get(0).size());
        reJsonObjectNoon.put("goClassLateName", getStuNames(DetailRecordNoonByTeaBean.get(0)));
        reJsonObjectNoon.put("backRoomLateCount", DetailRecordNoonByTeaBean.get(1).size());
        reJsonObjectNoon.put("backRoomLateName", getStuNames(DetailRecordNoonByTeaBean.get(1)));
        reJsonObjectNoon.put("notRoomCount", DetailRecordNoonByTeaBean.get(2).size());
        reJsonObjectNoon.put("notRoomName", getStuNames(DetailRecordNoonByTeaBean.get(2)));
        reJsonObjectNoon.put("askLeaveCount", DetailRecordNoonByTeaBean.get(3).size());
        reJsonObjectNoon.put("askLeaveCountName", getStuNames(DetailRecordNoonByTeaBean.get(3)));
        // reJsonObjectNoon.put("旷课人数", DetailRecordNoonByTeaBean.get(4).size());
        // reJsonObjectNoon.put("旷课姓名", DetailRecordNoonByTeaBean.get(4));
        reJsonArray.add(reJsonObjectNoon);
//      3、第三步晚上信息
        List<List<String>> DetailRecordNightByTeaBean;
        DetailRecordNightByTeaBean = getDetailRecordNightByTea(getTableName(), classId, schoolCode);
        JSONObject reJsonObjectNight = new JSONObject();
        reJsonObjectNight.put("goClass", "晚上");
        reJsonObjectNight.put("goClassLateCount", DetailRecordNightByTeaBean.get(0).size());
        reJsonObjectNight.put("goClassLateName", getStuNames(DetailRecordNightByTeaBean.get(0)));
        reJsonObjectNight.put("backRoomLateCount", DetailRecordNightByTeaBean.get(1).size());
        reJsonObjectNight.put("backRoomLateName", getStuNames(DetailRecordNightByTeaBean.get(1)));
        reJsonObjectNight.put("notRoomCount", DetailRecordNightByTeaBean.get(2).size());
        reJsonObjectNight.put("notRoomName", getStuNames(DetailRecordNightByTeaBean.get(2)));
        reJsonObjectNight.put("askLeaveCount", DetailRecordNightByTeaBean.get(3).size());
        reJsonObjectNight.put("askLeaveCountName", getStuNames(DetailRecordNightByTeaBean.get(3)));
        // reJsonObjectNight.put("旷课人数", DetailRecordNightByTeaBean.get(4).size());
        // reJsonObjectNight.put("旷课姓名", DetailRecordNightByTeaBean.get(4));
        reJsonArray.add(reJsonObjectNight);
        return reJsonArray;
    }

    /**
     * 晚上的详细考勤情况
     * @param tableName
     * @param classId
     * @param schoolCode
     * @return
     */
    private List<List<String>> getDetailRecordNightByTea(String tableName, String classId, Integer schoolCode) {
        List<List<String>> reList = new ArrayList<>();
        // 获取系统当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String curTime = df.format(new Date());// new Date()为获取当前系统时间
//		SimpleDateFormat askdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
//		String askcurTime = askdf.format(new Date());// new Date()为获取当前系统时间
        List<String> goClassLate = new ArrayList<>();
        List<String> backRoomLate = new ArrayList<>();
        List<String> notRoom = new ArrayList<>();
        List<String> askLeave = new ArrayList<>();
        List<String> truant = new ArrayList<>();
//	        查找这个班级有哪些人
        List<StudentEntity> studentInformationBeans = studentMapper.listClassStu(classId, schoolCode);
        List<String> notRoomtemp = new ArrayList<>();
        List<String> allClassLiveName = new ArrayList<>();
//	    这个班级的人 有些在passrecord表里有些没有在
        for (StudentEntity studentInformationBean : studentInformationBeans) {
//                查询当天请假的
            LeaveRecordEntity leaveRecordBean = kaoqinMapper.getLeaveRecord(studentInformationBean.getId());
//                当天请假的
            if (leaveRecordBean != null) {
                askLeave.add(studentInformationBean.getStudentName());
                notRoomtemp.add(studentInformationBean.getStudentName());
            }

//	            如果是住校生 就加入住校生的list中
            if (studentInformationBean.getIsliveinschool() == 1) {
                allClassLiveName.add(studentInformationBean.getStudentName());
            }
            PassRecordBean passRecordBean = kaoqinMapper.getPassRecord(tableName, studentInformationBean.getStudentThdid());
            if (passRecordBean != null) {
//	            在考勤表里
//	            晚上上课迟到
                if (passRecordBean.getFlag() == 9) {
                    goClassLate.add(studentInformationBean.getStudentName());
                    notRoomtemp.add(studentInformationBean.getStudentName());
                }
//	            晚上归寝迟到
                if (passRecordBean.getFlag() == 4) {
                    backRoomLate.add(studentInformationBean.getStudentName());
                    notRoomtemp.add(studentInformationBean.getStudentName());
                }
//	            正常归寝的
                if (passRecordBean.getFlag() == 0) {
                    notRoomtemp.add(studentInformationBean.getStudentName());
                }
            }
        }
//	    班级的住校生-晚上上课迟到的-晚上归寝迟到的-请假的-正常的=未归寝的
        Date current = new Date();
        if (current.after(StuRecordService.date8))
            for (String s : allClassLiveName) {
                if (!notRoom.contains(s)) {
                    notRoom.add(s);
                }
            }
        reList.add(goClassLate);
        reList.add(backRoomLate);
        reList.add(notRoom);
        reList.add(askLeave);
        reList.add(truant);
        return reList;

    }

    /**
     * 中午的详细考勤情况
     * @param tableName
     * @param classId
     * @param schoolCode
     * @return
     */
    private List<List<String>> getDetailRecordNoonByTea(String tableName, String classId, Integer schoolCode) {

        List<List<String>> reList = new ArrayList<>();
        // 获取系统当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String curTime = df.format(new Date());// new Date()为获取当前系统时间
//		SimpleDateFormat askdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
//		String askcurTime = askdf.format(new Date());// new Date()为获取当前系统时间
        List<String> goClassLate = new ArrayList<>();
        List<String> backRoomLate = new ArrayList<>();
        List<String> notRoom = new ArrayList<>();
        List<String> askLeave = new ArrayList<>();
        List<String> truant = new ArrayList<>();
//	        查找这个班级有哪些人
        List<StudentEntity> studentInformationBeans = studentMapper.listClassStu(classId, schoolCode);
//	        这个班级的人 有些在passrecord表里有些没有在
        for (StudentEntity studentInformationBean : studentInformationBeans) {
//	        没在打卡考勤表里查询当天请假的
            LeaveRecordEntity leaveRecordBean = kaoqinMapper.getLeaveRecord(studentInformationBean.getId());
            if (leaveRecordBean != null) {
                askLeave.add(studentInformationBean.getStudentName());
            }
            PassRecordBean passRecordBean = kaoqinMapper.getPassRecord(tableName, studentInformationBean.getStudentThdid());
            if (passRecordBean != null) {
//	            在考勤表里
//	            下午上课迟到
                if (passRecordBean.getFlag() == 3 || passRecordBean.getFlag() == 8) {
                    goClassLate.add(studentInformationBean.getStudentName());
                }
//	            下午归寝迟到
                if (passRecordBean.getFlag() == 2) {
                    backRoomLate.add(studentInformationBean.getStudentName());
                }
            }
        }
        reList.add(goClassLate);
        reList.add(backRoomLate);
        reList.add(notRoom);
        reList.add(askLeave);
        reList.add(truant);
        return reList;

    }




    /**
     * 早上的详细情况
     * @param tableName
     * @param classId
     * @param schoolCode
     * @return
     */
    private List<List<String>> getDetailRecordMorByTea(String tableName, String classId, Integer schoolCode) {
        List<List<String>> reList = new ArrayList<>();
        // 获取系统当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String curTime = df.format(new Date());// new Date()为获取当前系统时间
//		SimpleDateFormat askdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
//		String askcurTime = askdf.format(new Date());// new Date()为获取当前系统时间
        List<String> goClassLate = new ArrayList<>();
        List<String> backRoomLate = new ArrayList<>();
        List<String> notRoom = new ArrayList<>();
        List<String> askLeave = new ArrayList<>();
        List<String> truant = new ArrayList<>();
//	        查找这个班级有哪些人
        List<StudentEntity> studentInformationBeans = studentMapper.listClassStu(classId, schoolCode);
//	        这个班级的人 有些在passrecord表里有些没有在
        for (StudentEntity studentInformationBean : studentInformationBeans) {
//	        查询当天请假的
            LeaveRecordEntity leaveRecordBean = kaoqinMapper.getLeaveRecord(studentInformationBean.getId());
            if (leaveRecordBean != null) {
                askLeave.add(studentInformationBean.getStudentName());
            }
            PassRecordBean passRecordBean = kaoqinMapper.getPassRecord(tableName, studentInformationBean.getStudentThdid());
            if (passRecordBean != null) {
//	            在考勤表里
                if (passRecordBean.getFlag() == 1 || passRecordBean.getFlag() == 7) {
                    goClassLate.add(studentInformationBean.getStudentName());
                }
            }
        }
        reList.add(goClassLate);
        reList.add(backRoomLate);
        reList.add(notRoom);
        reList.add(askLeave);
        reList.add(truant);
        return reList;
    }

    //
//    // 根据course_id得到处理之后的班级名称
//    public String getClassName(String course_id) throws UserException {
//        String name = null;
//        try {
//            name = schoolDao.getClassNameByCourseId(course_id);
//            name = name.replace("20", "");
//        } catch (SQLException e) {
//            e.printStackTrace();
//            throw new UserException("查询班级名称失败");
//        }
//        return name;
//    }
//
//    // 封装记录的函数
    private void record(JSONObject typeObj, int classLate, int dormitoryLate, int leave, int real, int total) {
        typeObj.put("col2", classLate);
        typeObj.put("col3", dormitoryLate);
        typeObj.put("col4", leave);
        typeObj.put("col5", real + "/" + total);
    }
//
//    // 获取年级的上午考勤信息
    private JSONArray getGradeMorningKaoqinInfo(String gradeId, Integer schoolCode) {
        JSONArray jsonArray = new JSONArray();
//        int dayType = getDayType();
        int dayType = 0;//TODO  ---这个字段要注意哦  弄的默认值 ---注释掉 了  现在 没有什么返校日 之类的了，
        // 得到这个年级的所有班级
        ArrayList<ClassEntity> classList = kaoqinMapper.getGradeClassList(gradeId, schoolCode);
        for (ClassEntity classEntity : classList) {
            // 每个班查询自己的
            JSONObject tmp = new JSONObject();
            tmp.put("id", classEntity.getId());
            tmp.put("col1", classEntity.getClassName());
            int morningLate = getMoningLateNum(getTableName(), classEntity.getId() + "");
            int leaveNum = getLeaveNum(classEntity.getId() + " ",schoolCode);
            int total = schoolMapper.getClassStuNum(classEntity.getId(), schoolCode) - leaveNum;
            int real = total - morningLate;
            if (dayType == 1) {
                real = kaoqinMapper.getIntersection(getTableName(), 10, classEntity.getId() + "");
            }
            record(tmp, morningLate, 0, leaveNum, real, total);
            jsonArray.add(tmp);
        }
        return jsonArray;
    }
//
//    // 保安队长查询请假学生信息
//    private JSONArray getLeaveRecord(String course_id) throws UserException {
//        JSONArray jsonArray = new JSONArray();
//        // 得到这个年级的所有班级
//        ArrayList<Object[]> gradeLst = new ArrayList<>();
//        try {
//            gradeLst = (ArrayList<Object[]>) kaoqinDao.getGradeInfo(course_id);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            throw new UserException("保安队查询年级信息失败");
//        }
//        try {
//            for (Object[] objects : gradeLst) {
//                JSONObject tmp = new JSONObject();
////				jsonArray.add("寝室");
////				jsonArray.add("班级");
////				jsonArray.add("姓名");
////				jsonArray.add("类型");
////				jsonArray.add("时间");
//                // 查询出 每个班的请假学生
//                List<LeaveRecordBean> leaveRecordBeans = getLeaveRecordList((String) objects[0]);
//                for (LeaveRecordBean leaveRecordBean : leaveRecordBeans) {
//                    tmp.put("id", (String) objects[0]);
//                    tmp.put("col1", null);
//                    tmp.put("col2", getClassName((String) objects[0]));
//                    tmp.put("col3", leaveRecordBean.getStudent_name());
//                    if (leaveRecordBean.getIsauthority() == 1) {
//                        tmp.put("col4", "已审批");
//                    } else {
//                        tmp.put("col4", "未审批");
//                    }
//                    Date date = leaveRecordBean.getStart_time();
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                    tmp.put("col5", dateFormat.format(date));
//                    tmp.put("col6",
//                            leaveRecordBean.getStudent_gender() != null ? leaveRecordBean.getStudent_gender() : "-");
//                    jsonArray.add(tmp);
//                }
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//            throw new UserException("保安队长查询学生请假失败");
//        }
//
//        return jsonArray;
//    }
//
//    // 获取年级的中午考勤信息
    private JSONArray getGradeNoonKaoqinInfo(String course_id, Integer schoolCode) {
        JSONArray jsonArray = new JSONArray();
//        int dayType = getDayType();
        int dayType = 0;//TODO  ---这个字段要注意哦  弄的默认值 ---注释掉 了  现在 没有什么返校日 之类的了，
        // 得到这个年级的所有班级
        ArrayList<ClassEntity> classList = kaoqinMapper.getGradeClassList(course_id, schoolCode);
        for (ClassEntity classEntity : classList) {
            // 每个班查询自己的
            JSONObject tmp = new JSONObject();
            tmp.put("id", classEntity.getId());
            tmp.put("col1", classEntity.getClassName());
            int noonInLateNum = getNoonInLateNum(getTableName(), classEntity.getId() + "");
            int noonOutLateNum = getNoonOutLateNum(getTableName(), classEntity.getId() + "");
            int leaveNum = getLeaveNum(classEntity.getId() + "",schoolCode);
            int total = schoolMapper.getClassStuNum(classEntity.getId(), schoolCode) - leaveNum;
            int real = total - noonInLateNum - noonOutLateNum;
            if (dayType == 1) {
                real = kaoqinMapper.getIntersection(getTableName(), 10, classEntity.getId() + "");
            }
            record(tmp, noonInLateNum, noonOutLateNum, leaveNum, real, total);
            jsonArray.add(tmp);
        }
        return jsonArray;
    }
//
//    // 获取年级的晚上考勤信息
    private JSONArray getGradeNightKaoqinInfo(String course_id, Integer schoolCode) {
        JSONArray jsonArray = new JSONArray();
        // 得到这个年级的所有班级
        ArrayList<ClassEntity> classList = kaoqinMapper.getGradeClassList(course_id, schoolCode);
        for (ClassEntity classEntity : classList) {
            // 每个班查询自己的
            JSONObject tmp = new JSONObject();
            tmp.put("id", classEntity.getId());
            tmp.put("col1", classEntity.getClassName());
            int nightInLate = getNightinLateNum(getTableName(), classEntity.getId() + "");
            int nightOutLate = getNightOutLateNum(getTableName(), classEntity.getId() + "");
            int realNum = kaoqinMapper.getLiveInSchoolNum(classEntity.getId() + "");
            int nightKaoqin = getNightKaoqinNum(getTableName(), classEntity.getId() + "");
            int leaveNum = getLeaveNum(classEntity.getId() + "",schoolCode);
            record(tmp, nightInLate, nightOutLate, leaveNum, nightKaoqin, realNum);
            jsonArray.add(tmp);
        }
        return jsonArray;
    }
//
//    // 拼接人名
    private String getStuNames(List<String> list) {
        String names = "";
        for (String s : list) {
            names = names + " " + s;
        }
        return names;
    }
//
//    // 返回标题
    @Override
    public JSONArray colTitle(int flag) {
        JSONArray jsonArray = new JSONArray();
        switch (flag) {
            case 1:
                jsonArray.add("寝室");
                jsonArray.add("班级");
                jsonArray.add("姓名");
                jsonArray.add("类型");
                jsonArray.add("时间");
                jsonArray.add("性别");
                break;
            case 2:
                jsonArray.add("班级");
                jsonArray.add("上课迟到");
                jsonArray.add("归寝迟到");
                jsonArray.add("请假/旷课");
                jsonArray.add("实到/应到");
                break;
            case 3:
                jsonArray.add("班级");
                jsonArray.add("姓名");
                jsonArray.add("类型");
                jsonArray.add("时间");
                jsonArray.add("性别");
                break;
        }
        return jsonArray;
    }
//
//    // 返回年级
//    public List<GradeEntity> gradeSchoolAllList(Integer schoolCode) {
//        return
//    }

    private String getTableName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        return "pass_record" + dateFormat.format(date);
    }
//
//    // 判断当天类型,暂时只管理返校日（即当天是否是周日）
//    private int getDayType() {
//        return StuRecordService.dayType;
//    }
//
//    // 根据年级班级ID查询出其班主任ID 在查询出对应班级的请假学生
//    private List<LeaveRecordBean> getLeaveRecordList(String course_id) throws SQLException {
//        return kaoqinDao.getLeaveRecordList(course_id);
//    }

    // 得到表名
    private String getTableName(String date) {
        String[] dateList = new String[3];
        if (date.contains("-")) {
            dateList = date.split("-");
            if (dateList[1].length() <= 1)
                dateList[1] = "0" + dateList[1];
            if (dateList[2].length() <= 1)
                dateList[2] = "0" + dateList[2];
        }
        return "pass_record" + dateList[0] + dateList[1] + dateList[2];
    }
}
